const gameBox = document.querySelector("#game-box");
const bird = document.querySelector("#bird");

// 【新增代码】得到4个管子
const pipe1_up = document.querySelector("#pipe1_up");
const pipe1_down = document.querySelector("#pipe1_down");
const pipe2_up = document.querySelector("#pipe2_up");
const pipe2_down = document.querySelector("#pipe2_down");
// 【新增代码】得到遮罩
const cover = document.querySelector('#cover');
// 【新增代码】得到重玩儿按钮
const restart = document.querySelector('#restart');
// 大地背景的x值
let landBgX = 0;
// 得到大地
const land = document.querySelector("#land");
let birdTop = 200;
let deltaTop = 0;
let f = 0;
let step = 0;
let birdRotate = 0;

// 【新增代码】管子1的left值
let pipe1Left = 480;
// 【新增代码】管子2的left值
let pipe2Left = 880;

// 【新管子】管子1的height值
let pipe1_up_h = 300;
// 【新管子】管子2的height值
let pipe2_up_h = 200;

let timer = setInterval(() => {
  deltaTop += 0.6;
  birdTop += deltaTop;
  if (birdTop < 0) {
    birdTop = 0;
  }
  // 小鸟的AABB盒之a1值
  let birdA1 = birdTop + 6;
  // 小鸟的AABB盒之a2值
  let birdA2 = birdTop + 28;
  // 小鸟的AABB盒之b1值
  let birdB1 = 170 + 6;
  // 小鸟的AABB盒之b1值
  let birdB2 = 170 + 45;
  // 在控制台输出小鸟的AABB盒数据
  console.log(birdA1, birdA2, birdB1, birdB2);
  bird.style.top = birdTop + "px";

  f++;
  // 【新增语句】每3帧扑腾一次翅膀
  if (f % 3 == 0) {
    step++;
    if (step > 2) step = 0;
    bird.style.backgroundPosition = -step * 100 + "% 0";
  }

  // 【新增代码】让小鸟旋转角度变化
  birdRotate += 3;
  bird.style.transform = "rotate(" + birdRotate + "deg)";

  // 【新增代码】管子移动
  pipe1Left -= 3;
  pipe2Left -= 3;
  // “倒腾”管子
  if (pipe1Left < -88) {
    pipe1Left = pipe2Left + 400;
    let pipe1_up_h = parseInt(Math.random() * 240) + 60;
    pipe1_up.style.height = pipe1_up_h + "px";
    pipe1_down.style.top = pipe1_up_h + 200 + "px";
    pipe1_down.style.height = 560 - pipe1_up_h - 200 + "px";
  } else if (pipe2Left < -88) {
    pipe2Left = pipe1Left + 400;
    let pipe2_up_h = parseInt(Math.random() * 240) + 60;
    pipe2_up.style.height = pipe2_up_h + "px";
    pipe2_down.style.top = pipe2_up_h + 200 + "px";
    pipe2_down.style.height = 560 - pipe2_up_h - 200 + "px";
  }
  // 【新增代码】让管子DOM元素跟随变量变化
  pipe1_up.style.left = pipe1Left + "px";
  pipe1_down.style.left = pipe1Left + "px";
  pipe2_up.style.left = pipe2Left + "px";
  pipe2_down.style.left = pipe2Left + "px";

  landBgX -= 3;
  land.style.backgroundPosition = landBgX + "px 0";

  // 【新代码】碰撞检测
  if (
    (birdB2 > pipe1Left && birdB1 < pipe1Left + 88 && birdA1 < pipe1_up_h) ||
    (birdB2 > pipe1Left &&
      birdB1 < pipe1Left + 88 &&
      birdA2 > pipe1_up_h + 200) ||
    (birdB2 > pipe2Left && birdB1 < pipe2Left + 88 && birdA1 < pipe2_up_h) ||
    (birdB2 > pipe2Left &&
      birdB1 < pipe2Left + 88 &&
      birdA2 > pipe2_up_h + 200) ||
    birdA2 > 560
  ) {
    clearInterval(timer);
    cover.style.opacity = 1;
    restart.style.top = '200px';
  }
}, 20);
gameBox.onclick = () => {
  deltaTop = -14;
  birdRotate = -80;
};
// 点击重玩儿按钮，刷新网页
restart.onclick = () => {
    location.reload();
    };
